package com.example.ffepeg.ffmTestIng;

import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;

public class XMLParserExample {

    public static void main(String[] args) {
        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                "<xml_result>\n" +
                "  <read_sentence lan=\"en\" type=\"study\" version=\"7.0.0.1020\">\n" +
                "      <rec_paper>\n" +
                "          <read_chapter accuracy_score=\"100.000000\" beg_pos=\"0\" content=\"examine\" end_pos=\"98\" except_info=\"0\" fluency_score=\"95.840600\" integrity_score=\"100.000000\" is_rejected=\"false\" reject_type=\"0\" score_pattern=\"loose\" standard_score=\"89.318940\" total_score=\"97.684080\" word_count=\"1\">\n" +
                "              <sentence accuracy_score=\"100.000000\" beg_pos=\"0\" content=\"examine\" end_pos=\"98\" fluency_score=\"90.840600\" index=\"0\" standard_score=\"84.318940\" total_score=\"95.684080\" word_count=\"1\">\n" +
                "                  <!-- 省略了word内部细节 -->\n" +
                "              </sentence>\n" +
                "          </read_chapter>\n" +
                "      </rec_paper>\n" +
                "  </read_sentence>\n" +
                "</xml_result>";

        try {
            // 创建DocumentBuilderFactory和DocumentBuilder
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();

            // 解析XML字符串
            Document document = builder.parse(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)));
            document.getDocumentElement().normalize(); // 标准化XML结构

            // 获取所有'read_chapter'节点
            NodeList readChapterNodes = document.getElementsByTagName("read_chapter");
            for (int i = 0; i < readChapterNodes.getLength(); i++) {
                Node node = readChapterNodes.item(i);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    Element element = (Element) node;
                    // 提取属性值
                    String accuracyScore = element.getAttribute("accuracy_score");
                    String integrityScore = element.getAttribute("integrity_score");
                    System.out.println("Accuracy Score: " + accuracyScore);
                    System.out.println("Integrity Score: " + integrityScore);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
